package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * admin 登录
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public ResponseResult login(AdUserDTO dto) {
        //1.校验参数
        String name = dto.getName();
        String password = dto.getPassword();
        if (StringUtils.isBlank(name)||StringUtils.isBlank(password)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户名和密码不能为空");
        }
        //2.根据用户名，查询对应的用户
        AdUser user = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        if (user==null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"用户不存在");
        }
        //3.对比输入的密码和数据库中的密码是否一致
        // MD5(输入密码+salt)
        String intPwd = DigestUtils.md5DigestAsHex((password + user.getSalt()).getBytes());
        if (!intPwd.equals(user.getPassword())) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //4.判断用户状态是否为 9(正常)
        if (user.getStatus()!=9) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }
        //5.重新设置时间
        user.setCreatedTime(new Date());
        this.updateById(user);
        //6.频发token jwt 令牌 返回响应结果：{token: ,user: }
        String token = AppJwtUtil.getToken(user.getId().longValue());
        AdUserVO userVO = new AdUserVO();
        BeanUtils.copyProperties(user,userVO);
        Map map = new HashMap<>();
        map.put("token",token);
        map.put("user",userVO);
        return ResponseResult.okResult(map);
    }
}